package utils;



import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.tika.Tika;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xuguoqing
 * @version 1.0
 * @description: 文件操作类
 * @date 2022/10/10 9:50
 */
@Slf4j
public class FileUtil {

    public static final String TMP_URL = "/tmp";

    /**
     * 将file转换为inputStream
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    public static InputStream file2InputStream(File file) throws Exception {
        return new FileInputStream(file);
    }


    public static void inputStream2File(InputStream initialStream,File targetFile) throws Exception{
        try  {
            Files.copy(
                    initialStream,
                    targetFile.toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }finally {
            initialStream.close();
        }
    }







    public static String getFileType(File dirFile) {
        Tika tika = new Tika();
        String fileType = "";
        try {
            fileType = tika.detect(dirFile);
        } catch (IOException e) {
            log.error("文件类型识别失败，错误信息：{}", e.getMessage(), e);
        }
        return fileType;
    }


    public static void deleteFile(String filePath){
        try {
            File dir = new File(filePath);
            if (dir.exists()) {
                FileUtils.forceDelete(dir);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }


    /**
     * 获取文件名称前缀
     * @param fileName
     * @return
     */
    public static String getPrefix(String fileName) {
        return getPrefix(fileName, false);
    }

    /**
     * 获取文件名称前缀
     * @param fileName
     * @return
     */
    public static String getPrefix(String fileName, boolean toLower) {
        if (fileName.contains(".")) {
            String prefix = fileName.substring(0,fileName.lastIndexOf("."));
            if (toLower) {
                return trimilSpace(prefix.toLowerCase());
            }
            return trimilSpace(prefix);
        }
        return "";
    }

    /**
     * @param input
     * @return
     */
    public static String trimilSpace(String input) {
        if (input == null) {
            return null;
        }
        String result = input.replaceAll("\u00A0", "").replaceAll("\u200B", "").replaceAll("\u2002", "")
                .replaceAll("\u200C", "").replaceAll("\u200D", "").replaceAll("\uFEFF", "").trim();
        if ("".equals(input)) {
            return null;
        }
        return result;
    }




    /**
     * 获取时间戳，每次获取的不同
     * @return
     */
    public synchronized static String getTimeStr() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date());
    }

    /**
     * 创建文件夹
     * @param path
     * @return
     */
    public static void createDir(String path){
        // 本地文件夹
        File localDir = new File(path);
        if (!localDir.exists()) {
            localDir.mkdirs();
        }
    }
    /**
     * 判断是文件压缩还是文件夹压缩
     * @param uncompressedPath
     * @return
     */
    public static boolean isDirCompress(String uncompressedPath) {
        File unzipFileDir = new File(uncompressedPath);
        File [] unzipFiles = unzipFileDir.listFiles();
        //文件夹压缩（TRUE）还是多文件压缩（FALSE）
        boolean isDirCompress = true;
        if(unzipFiles!=null&&unzipFiles.length==1&&!unzipFiles[0].isDirectory()){
            isDirCompress = false;
        }
        return isDirCompress;
    }









}
